package com.gitee.zw.rule.data;

import com.ibm.risk.irmp.common.utils.BeanMapUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.kie.api.definition.type.FactType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class SqlDataExporter implements DataExporter {

    @Autowired
    NamedParameterJdbcTemplate jdbcTemplate;

    @Override
    public String getDataAccessType() {
        return "SQL";
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public <T> int exportData(Map<String, Object> params, Collection<T> dataList) {
        if (dataList.isEmpty()) {
            log.info("No data to export");
            return 0;
        }
        List<Map<String, Object>> paramList;
        String sqlParam = (String) params.get(getDataAccessType());
        if (StringUtils.isEmpty(sqlParam)) {
            log.error("SQL is empty");
            return 0;
        }
        String[] sqls = sqlParam.split(";");
        if (dataList.iterator().next() instanceof Map<?, ?>) {
            paramList = (List<Map<String, Object>>) dataList;
        } else {
            if (params.get(FACT_TYPE) != null) {
                FactType factType = (FactType) params.get(FACT_TYPE);
                paramList = dataList.stream().map(m -> factType.getAsMap(m)).toList();
            } else {
                paramList = dataList.stream().map(m -> BeanMapUtils.beanToMap(m)).toList();
            }
        }
        int cnt = 0;
        for (String sql : sqls) {
            int[] cnts = jdbcTemplate.batchUpdate(sql, paramList.toArray(new Map[paramList.size()]));
            for (int i : cnts) {
                cnt += i;
            }
        }
        return cnt;
    }
}
